<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 表格 -->
    <!-- <title-name :title="$route.meta.title"></title-name> -->
    <a-row :gutter="10" class="page-height">
      <a-col :span="6">
        <a-card style="border-right:1px solid #d9d9d9" class="page-height-tree">
          <!-- 公司组织树搜索 -->
          <tree-project ref="treeOrganization" @loader="search" :query="treeQuery" :selectedKeys.sync="selectedKeys"
            :selectOptions.sync="selectOptions" :collapsed.sync="collapsed"></tree-project>
        </a-card>
      </a-col>
      <a-col :span="18" class="permission-collapsed page-height-list-wrapper" style="background:#fff">
        <div>
          <!-- 搜索 -->
          <searchData :searchData="searchArr" @search="search" @getOptions="getTitle"> </searchData>
          <div class="table-operator page-height-list">
            <a-collapse :bordered="false" v-model="activeKey" expand-icon-position="right">
              <a-collapse-panel style="background: #e6f3fc; border: none" :showArrow="false" class="mb12">
                <template slot="header">
                  <a-row type="flex" justify="space-between" align="middle" style="width: 100%">
                    <div>
                      <a-icon style="color: #108ee9" type="exclamation-circle" />
                      <span>总计 {{ totalSize }}</span>
                      <a-divider type="vertical"></a-divider>
                      <span>
                        已选择
                        <a>{{ rowSelection.selectedRowKeys.length || 0 }}</a> 项
                      </span>
                      <a-divider type="vertical"></a-divider>
                      <span>合格率{{ countTable.passRate || 0 }}</span>
                    </div>
                    <div>
                      <a-button :disabled="selectedKeys.length === 0" :loading="loading" type="primary"
                        @click.stop="getSummary(0)">汇总所有</a-button>
                      <a-button :loading="loading" type="primary"
                        :disabled="selectedKeys.length === 0 || rowSelection.selectedRowKeys.length === 0"
                        @click.stop="getSummary(1)">汇总选中</a-button>
                      <a class="btn_right">
                        <span>{{ activeKey.length > 0 ? '收起' : '展开' }}详细</span>
                        <a-icon :type="activeKey.length > 0 ? 'up' : 'down'" />
                      </a>
                    </div>
                  </a-row>
                </template>
                <div>
                  <a-spin :spinning="spinning()">
                    <a-tabs v-model="args.type" @change="switchSummary">
                      <a-tab-pane v-for="item in tabList" :key="item.projectTypeId"
                        :tab="item.projectTypeName"></a-tab-pane>
                    </a-tabs>
                  </a-spin>
                  <list-table ref="tableSummary" class="deskAccount-table" tableLayout="fixed" size="default"
                    :rowKey="(record) => record.id" :columns="columnsSummary" :request="loadDataSummary" :alert="true"
                    show-size-changer show-quick-jumper :showPagination="false" style="background: #fff"></list-table>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </div>
          <list-table ref="table" class="deskAccount-table" tableLayout="fixed" size="default"
            :rowSelection="rowSelection" rowKey="id" :columns="columns" :request="loadData" show-size-changer
            show-quick-jumper showPagination="auto">
            <template slot="action" slot-scope="text, record">
              <a-tooltip>
                <template slot="title">{{ `${record.bimNumber ? '已' : '未'}关联BIM模型` }}</template>
                <a-icon @click.stop="handleRelease(record)" type="link"
                        :style="{ color: record.bimNumber ? '#1890ff' : '#ccc' }" />
                <a-divider v-btnPermission="'qm_011_loo_02'" type="vertical"></a-divider>
              </a-tooltip>
              <a v-btnPermission="'qm_011_loo_02'" @click="handleManage(2, record)">查看</a>
              <a-divider v-btnPermission="'qm_011_edi_01'" type="vertical"></a-divider>
              <a v-btnPermission="'qm_011_edi_01'" @click="handleManage(1, record)">编辑</a>
            </template>
            <template slot="expandedRowRender" slot-scope="record">
              <a-row>
                <a-col :span="24">原因分析：{{ record.reason || '无' }}</a-col>
                <a-col :span="24" v-for="item in record.checkItemInfo" :key="item.id">
                  <a-row style="width: 70%">
                    <a-col :span="8">检查项名称：<ellipsis tooltip :length="22">{{ item.checkItemName }}</ellipsis></a-col>
                    <a-col :span="8">测量值：{{ item.measuringValue }}<span v-if="item.judgmentTypeCode != 2">{{ item.unit
                    }}</span></a-col>
                    <a-col :span="8">测量结果：{{ item.measuringResult }}</a-col>
                  </a-row>
                </a-col>
              </a-row>
            </template>
          </list-table>
        </div>
      </a-col>
    </a-row>
    <!-- BIM模型列表弹窗 -->
    <BimView
            ref="bimView"
            :visible.sync="visibleBim"
            :zIndex="949"
            :extraParams="extraParams"
            @handleOpen="handleOpen"
    />
    <!-- 关联BIM模型弹窗 -->
    <BimRelease
            ref="bimRelease"
            :zIndex="950"
            :destroyOnClose="true"
            :isRelease="false"
            :visible.sync="visibleRelease"
            :modelList="modelList"
    />
  </base-breadcrumb>
</template>

<script>
  import { Ellipsis } from '@/components' // 表格
import { table } from '@/api/quality/reality' // api
import cloneDeep from 'lodash.clonedeep' // 深拷贝
import { Collapse } from 'ant-design-vue' // ant
import TreeProject from '@/components/businessComponents/TreeProject' // 树
import SelectProjectStatus from '@/views/quality/components/SelectProjectStatus' // 项目状态
import BimView from '@/components/Dialog/BimView' // BIM模型关联列表
import BimRelease from '@/components/Dialog/BimRelease'
import { getList } from '@/api/bimIntegrate/bimModel' // BIM模型关联
const columns = [
  {
    title: '分公司',
    ellipsis: true,
    dataIndex: 'branchCompanyName',
  },
  {
    title: '项目',
    ellipsis: true,
    dataIndex: 'projectName',
  },
  {
    title: '测量点位编号',
    ellipsis: true,
    dataIndex: 'measuringPointCode',
  },
  {
    title: '测量点名称',
    ellipsis: true,
    dataIndex: 'measurePointName',
  },
  {
    title: '区域位置',
    ellipsis: true,
    dataIndex: 'checkArea',
  },
  {
    title: '分项工程',
    ellipsis: true,
    dataIndex: 'subItem',
  },
  {
    title: '测量人',
    ellipsis: true,
    dataIndex: 'measurePeople',
  },
  {
    title: '测量时间',
    ellipsis: true,
    dataIndex: 'measurementDate',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    align: 'center',
    scopedSlots: { customRender: 'action' },
  },
]
const columnsSummary = [
  {
    title: '分公司名称',
    dataIndex: 'name',
  },
  {
    title: '测量点数量',
    dataIndex: 'measuringNo',
  },
  {
    title: '合格率',
    dataIndex: 'passRate',
  },
]

export default {
  name: 'a' + Date.now(),
  components: {
    Ellipsis,
    TreeProject,
    ACollapse: Collapse,
    ACollapsePanel: Collapse['Panel'],
    BimView,
    BimRelease
  },
  data() {
    this.columns = columns
    this.columnsSummary = columnsSummary
    return {
      visibleRelease: false,
      visibleBim: false,
      extraParams: {
       projectId: null,
        subAreaId: null
      },
      modelList: [],
      treeQuery: {}, // 树列表请求参数
      tabList: [],
      collapsed: false,
      defaultTabs: [
        {
          projectTypeName: '按分公司汇总',
          projectTypeId: '0',
        },
        {
          projectTypeName: '按项目汇总',
          projectTypeId: '1',
        },
      ],
      selectedKeys: [],
      selectOptions: {},
      activeKey: [],
      rowSelection: {
        selectedRowKeys: [],
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.isChildren,
          },
        }),
        onChange: (e) => {
          this.countTable.tableCount = e.length
          this.rowSelection.selectedRowKeys = e
        },
      },
      isShow: false,
      queryParam: {}, // 查询参数
      // 统计数据
      countTable: {
        passRate: 0, // 合格率
      },
      args: {
        type: '0',
        ids: [], // 表格选中集合
      },
      totalSize: 0,  // 数据总计
      // 盒子高度
      boxHeight: 0,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        if (this.selectedKeys.length > 0) {
          // 格式化参数
          if (this.queryParam.date?.length > 0) {
            this.queryParam.beginDate = this.queryParam.date[0]
            this.queryParam.endDate = this.queryParam.date[1]
            delete this.queryParam.date
          }
          const requestParameters = Object.assign({}, parameter, this.queryParam, { treeId: this.selectedKeys[0] })
          return table.postList(requestParameters).then((res) => {

            this.totalSize = res.totalSize;
            // 若存在选中项则清除
            this.rowSelection.selectedRowKeys.length > 0 && this.$refs.table.clearSelected()
            return res
          })
        }
      },
      loading: false, // 汇总按钮加载控件
      isInit: false, // 汇总初始化标识
      loadDataSummary: (parameter) => {
        let that = this
        if (!that.isInit) {
          return false
        }
        // 格式化参数
        if (this.queryParam.date?.length > 0) {
          this.queryParam.beginDate = this.queryParam.date[0]
          this.queryParam.endDate = this.queryParam.date[1]
          delete this.queryParam.date
        }
        const requestParameters = Object.assign({}, parameter, this.queryParam, that.args, {
          treeId: that.selectedKeys[0],
        })
        // 若tab项为工程类别
        if (requestParameters.type !== '0' && requestParameters.type !== '1') {
          requestParameters.projectTypeId = requestParameters.type // 添加工程类别id
          requestParameters.type = '3' // 修改汇总类型为工程类别
        }
        that.loading = true
        return table
          .count(requestParameters)
          .then((res) => {
            console.log(res, 'hahhahah');
            // 深拷贝回调对象
            that.loading = false
            let datas = cloneDeep(res)

            console.log(datas, '4342442');
            datas.data = res.data.realityTableCountLists // 列表对象
            that.countTable.passRate = res.data.passRate
            return datas
          })
          .catch((res) => {
            that.loading = false
          })
      },
      form: {},
      scrollerHeight: null
    }
  },
  computed: {
    // 搜索配置
    searchArr() {
      return [
        // 搜索框
        // {
        //   name: '工程类别',
        //   type: SelectProjectType,
        //   valueKey: 'projectTypeId',
        //   ref:'SelectProjectType',
        //   id: this.selectOptions.parentId ? this.selectedKeys[0] : '', // 工程类别列表根据组织id联动
        // },
        // {
        //   name: '分部分项',
        //   type: SelectTreeSubItem,
        //   valueKey: 'subItemId',
        // },
        {
          name: '测量时间',
          type: 'dateRange',
          value: 'date',
          attr: {
            valueFormat: 'YYYY-MM-DD',
          },
        },
        {
          name: '测量点名称',
          type: 'input',
          value: 'measurePointName',
        },
        {
          name: '测量人',
          type: 'input',
          value: 'measurePeople',
        },
        {
          name: '项目状态',
          type: SelectProjectStatus,
          valueKey: 'projectStatus'
        }
      ]
    },
  },
  mounted() {
    this.$refs.treeOrganization.getList().then((res) => {
      this.search()
    })
  },
  methods: {
    /**
     * @description: 打开模型
     * @param {Array} data：模型列表或者模型选中项
     */
    handleOpen(data) {
      this.modelList = data
      console.log(this.modelList,2222)
      this.visibleBim = false
      this.visibleRelease = true
    },
    /**
     * @description: 查看关联的BIM模型
     * @param {*} record：业务对象
     * @return {*}
     */
    /**
     * @description: 打开模型列表
     * @param {Object} data：节点数据
     */
    handleRelease(data) {
      // data.projectId = '658560713194872832'
      // data.respAreaNodeId = '730255249968861184'
      // data.bimNumber = 2
      this.extraParams.projectId = data.projectId
      if (data.bimNumber > 0) {
        this.extraParams.subAreaId = data.respAreaNodeId
        // 关联数量大于1则打开模型列表，只有一个时则直接打开模型详情
        if (data.bimNumber > 1) {
          this.visibleBim = true
        } else {
          let args = { pageSize: 10, pageNum: 1, param: { projectId:  data.projectId, subAreaId: data.respAreaNodeId } }
          data.loading = true
          // 请求模型参数
          getList(args)
            .then((res) => {
              if (res.code === '0') {
                const record = res.data?.list?.[0]
                const params = [{ id: record.id, modelId: record.modelFileId, version: record.modelFileVersion, modelTitle: record.modelName }]
                this.handleOpen(params)
              }
            })
            .finally(() => {
              data.loading = false
            })
        }
      }
    },
    // tabs的加载控件，绑定工程类别loading
    spinning() {
      return this.$refs.searchData?.$refs.SelectProjectType?.fetching ?? false
    },
    // 切换汇总信息
    switchSummary(e) {
      this.args.type = e
      if (e === '0' || e === '1') {
        this.columnsSummary[0].title = ['分公司名称', '项目名称'][e]
      } else {
        this.columnsSummary[0].title = '分部分项'
      }
      this.$nextTick(() => {
        this.$refs.tableSummary.refresh(true)
      })
    },
    // 汇总
    getSummary(e) {
      let that = this
      if (!e) {
        that.args.ids = []
        that.args = Object.assign(that.args, that.$refs.searchData.form.getFieldsValue())
      } else {
        that.args.ids = that.rowSelection.selectedRowKeys
      }
      if (that.activeKey.length == 0) {
        that.activeKey = ['0']
      }
      that.$nextTick(() => {
        !that.isInit && (that.isInit = true)
        that.$refs.tableSummary.refresh(true)
      })
    },
    // 获取工程类别列表
    getTitle(e) {
      this.tabList = this.defaultTabs.concat(
        e.map((item) => {
          item.projectTypeName = item.projectTypeName + '分部分项汇总'
          return item
        })
      )
    },
    // 搜索
    search(value) {
      if (value) {
        this.queryParam = Object.assign(value, this.form)
      }
      // 若存在项目状态，则先请求树，再请求表格
      if (value?.projectStatus) {
        this.$set(this.treeQuery, 'projectStatus', value.projectStatus)
      } else {
        this.$set(this.treeQuery, 'projectStatus', null)
      }
      this.$refs.treeOrganization.getList().then(() => {
        this.$refs.table?.refresh(true)
      })
    },
    // 操作栏
    handleManage(e, record) {
      let query = {
        editModel: e,
      }
      if (record) {
        query.id = record.id
      }
      this.$router.push({
        name: '/quality/measuredAmount/deskAccount/deskAccountEdit',
        query,
      })
    },
  },
}
</script>
<style lang="less">
.deskAccount-table .ant-table-fixed-right .ant-table-expanded-row {
  height: 100px;
}

.deskAccount-table .ant-table-expanded-row {
  height: 100px;
}
</style>
